#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/4 10:58
# @Author  : Andrewq
# @Site    : nope
# @File    : DepartmentInfoModel.py
# @Software: PyCharm
import datetime

from flask import current_app
from sqlalchemy import func

from .models import EmployeeInfo, DepartmentInfo
from .. import db
from ..utils import commons
from ..utils.response_code import RET


class DepartmentInfoManager(DepartmentInfo):
    @classmethod
    def get_department_person_statistics(cls):
        filter_list = []
        filter_list.append(cls.DepartmentID == EmployeeInfo.DepartmentID)
        try:
            statistics = db.session.query(cls.DepartmentID,
                                          cls.DepartmentName,
                                          func.count(EmployeeInfo.UserID).label('number')
                                          ).filter(*filter_list) \
                .group_by(cls.DepartmentID, cls.DepartmentName)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        if not statistics.first():
            return {'code': RET.NODATA, 'message': '没有部门的人员统计数据'}

        statistics_data = commons.query_to_dict(statistics.all())

        back_data = []

        for data in statistics_data:
            back_data.append({'index': data.get('DepartmentName'), 'number': data.get('number')})

        return {'code': RET.OK, 'message': '统计部门人员的数据成功', 'data': back_data}

    @classmethod
    def get_department_all_info(cls):
        filter_list = []

        try:

            departments = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        if not departments.first():
            return {'code': RET.NODATA, 'message': '没有员工数据'}

        back_data = commons.query_to_dict(departments.all())

        return {'code': RET.OK, 'message': '查询用户信息成功', 'data': back_data}

    @classmethod
    def add_department_info(cls, **kwargs):
        try:
            department_ID = (datetime.datetime.now()).strftime('%Y%m%d%H%M%S')

            Department = DepartmentInfo(
                DepartmentID=department_ID,
                DepartmentName=kwargs.get('DepartmentName')
            )

            db.session.add(Department)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        data = commons.query_to_dict(Department)

        return {'code': RET.OK, 'message': '添加数据成功', 'data': data}

    @classmethod
    def get_department_info_by_tags(cls, **kwargs):
        tag_name = kwargs.get('tag')
        filter_list = []

        if tag_name == '部门ID':
            filter_list.append(cls.DepartmentID.contains(kwargs.get('keyword')))

        elif tag_name == '部门名':
            filter_list.append(cls.DepartmentName.contains(kwargs.get('keyword')))

        try:
            result = db.session.query(cls).filter(*filter_list)

            if not result.first():
                return {'code': RET.NODATA, 'message': "没有查询结果"}

            back_data = commons.query_to_dict(result.all())

            return {'code': RET.OK, 'message': '查询数据成功', 'data': back_data}

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

    @classmethod
    def delete_employee_info_list(cls, **kwargs):
        data = kwargs.get('data')
        ID_list = []
        try:
            for item in data:
                ID_list.append(item['data']['DepartmentID'])
            for ID in ID_list:
                filter_list = []
                filter_list.append(cls.DepartmentID == ID)

                department = db.session.query(cls).filter(*filter_list)

                if not department.first():
                    return {'code': RET.NODATA, 'message': '没有用户数据'}

                department.delete()
                db.session.commit()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '成功删除数据', 'data': data}

    @classmethod
    def delete_department_info(cls, **kwargs):
        filter_list = []

        filter_list.append(cls.DepartmentID == kwargs.get('DepartmentID'))

        try:
            department = db.session.query(cls).filter(*filter_list)

            if not department.first():
                return {'code': RET.NODATA, 'message': '没有用户数据'}

            department.delete()
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        back_data = {
            'DepartmentID': kwargs.get('DepartmentID'),
        }

        return {'code': RET.OK, 'message': '删除用户数据成功', 'data': back_data}

    @classmethod
    def edit_department_info(cls, **kwargs):
        filter_list = []

        try:
            filter_list.append(cls.DepartmentID == kwargs.get('DepartmentID'))

            Department = db.session.query(cls).filter(*filter_list)

            if not Department.first():
                return {'code': RET.NODATA, 'message': '没有该部门数据'}

            Department.update({'DepartmentName': kwargs.get('DepartmentName')})
            db.session.commit()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '修改信息成功', 'data': kwargs}
